import React, {useRef} from "react";
import {Button, Card, message, Modal} from "antd";
import ProTable, {ActionType, ProColumns, RequestData} from "@ant-design/pro-table";
import {DeleteOutlined, PlusOutlined} from "@ant-design/icons";
import {ParamsType} from "@ant-design/pro-provider";
import interfaceService from "@/services/interface";
import {transformParams} from "@/utils/utils";
import {InterfaceVO} from "@/types/interface";
import GridContainer from "@/components/GridContainer";
import styles from "./index.less";
import FunctionList from "../components/List";
import {InterfaceCreateForm} from "../Form";

const queryList= async (params:any, sorter:any, filter:any): Promise<RequestData<InterfaceVO>> => {
  if(params&&params.functionId){
    const  dto = transformParams(params, sorter);
    const response=await interfaceService.queryAssignedList(dto);
    const {data}=response;
    return {
      success:true,
      data: data,
    };
  }
  return {
    success:true,
    data: [],
  };
}

const _delete=async (params:any)=>{
  const response=await interfaceService.deleteFunctionInterfaceRelation(params)
  const {exception}=response;
  if(!exception){
    message.success('删除成功');
  }
}

interface InterfaceListProps {
  params?:ParamsType;
  actionRef?:((actionRef: ActionType) => void);
}

const InterfaceList: React.FC<InterfaceListProps> = (props:InterfaceListProps) => {

  const actionRef = useRef<ActionType>();

  const onActionRef=(ref:ActionType)=>{
    actionRef.current=ref;
    props.actionRef&&props.actionRef(ref);
  }

  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */

  const showDeleteModal=async (record:InterfaceVO) => {
    Modal.confirm({
      title: '是否移除该接口',
      content: record.name,
      onOk:()=>{
        // @ts-ignore
        _delete({interfaceId: record.id,...props.params});
        const reloadAndRest=actionRef.current?.reset;
        reloadAndRest&&reloadAndRest();
      }
    })
  }


  const columns: ProColumns<InterfaceVO>[] = [
    {
      title: '接口名称',
      align:'left',
      dataIndex: ['name'],
    },
    {
      title: '接口路径',
      align:'left',
      dataIndex: ['path'],
    },
    {
      title: '接口方法',
      align:'center',
      dataIndex: ['method'],
    },
    {
      title: '操作',
      align:'center',
      dataIndex: 'action',
      search:false,
      render:(dom,entity,index,action,schema)=>{
        return (
          <Button
            type="link"
            icon={<DeleteOutlined />}
            onClick={()=>showDeleteModal(entity)}
          />
        )
      }
    },
  ];

  return (
    <ProTable<InterfaceVO>
      actionRef={onActionRef}
      // @ts-ignore
      rowKey={((record) => record.id)}
      params={props.params}
      search={false}
      pagination={false}
      toolBarRender={false}
      request={queryList}
      columns={columns}
    />
);
};

interface Props {

}

interface State{
  selectedKeys:(string|number)[];
  createModalVisible:boolean;
}

export default class List extends React.Component<Props,State> {

  actionRef:ActionType | undefined;

  state={
    selectedKeys:[],
    createModalVisible:false,
  }

  onSelect=(selectedKeys: (string|number)[])=>{
    if(selectedKeys.length>0){
      this.setState({selectedKeys});
    }
  }

  onReset=()=>{
    const reloadAndRest=this.actionRef?.reset;
    reloadAndRest&&reloadAndRest();
    this.setState({createModalVisible:false});
  }

  onHide=()=>{
    this.setState({createModalVisible:false});
  }

  onClick=()=>{
    this.setState({createModalVisible:true});
  }

  render() {

    const {
      selectedKeys,createModalVisible
    }=this.state;

    const params=selectedKeys.length>0?{
      functionId:selectedKeys[0]
    }:undefined

    return (
      <GridContainer>
        <FunctionList
          selectedKeys={selectedKeys}
          onSelect={this.onSelect}
        />
        <Card
          bordered={false}
          title={'接口列表'}
          className={styles.right}
          extra={
            <Button
              type="primary"
              onClick={this.onClick}
              disabled={!(selectedKeys.length>0)}
            >
              <PlusOutlined />
              关联接口
            </Button>
          }
        >
          <InterfaceList
            params={params}
            actionRef={(actionRef)=>this.actionRef=actionRef}
          />
          {createModalVisible&&(
            <InterfaceCreateForm
              params={params}
              onReset={this.onReset}
              visible={createModalVisible}
              onVisibleChange={this.onHide}
            />
          )}
        </Card>
      </GridContainer>
    );
  }
}

